<template>
    <div class="common-layout">
    <!---侧边栏--->
    <el-container>
     <Menu/>
      <!---上边栏--->
      <el-container >
        <el-header class="header">
              <span class="text-large font-600 mr-3"><h2>信息总览</h2></span>
        </el-header>
        <el-main style="margin-left: -300px;">
    <div class="circleChart">
        <div id="myChart1" class="chartItem"></div>
        <div id="myChart2" class="chartItem"></div>
    </div>

    <div class="rectChart1">
        <div id="myChart3" class="chartItem"></div>
      <div id="myChart4" class="chartItem"></div>
    </div>

    <div class="rectIntroduction">
        <p>社团数</p>
        <p style = "margin-left: 550px;">成员数</p>
    </div>

</el-main>
      </el-container>
    </el-container>
  </div>
  </template>
  
  <script>
  import {defineComponent, toRefs, reactive, onMounted, watch} from 'vue'
  import * as echarts from 'echarts'
  import Menu from "@/pages/SystemController/Menu.vue";
  import axios from "axios";
  const tableData=reactive([])
  const collageData=reactive({
    'cs':0,
    'mapping':0,
    'literature':0,
    'hony':0,
  })
  const typeData=reactive({
    '0':0,
    '1':0,
    '2':0,
    '3':0,
    '4':0,
    '5':0,
  })
  const clubNum=reactive([])

  const numberNum=reactive([])

  //初始数据
  const pages = reactive({
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页显示的条目数
    total: 100, // 总条目数
  });

  // 监听页码变化
  watch(() => pages.currentPage, (newPage) => {
    // 这里可以请求数据或使用计算属性更新数据
    // 例如: fetchData(newPage);
  });

  // 分页变化事件处理
  const handleCurrentChange = (newPage) => {
    pages.currentPage = newPage;
    getList()
  };

  async function getList() {
    try {
        // 第一次调用：获取社团列表数据
        const clubRes = await axios.get('http://localhost:8080/club/list', {
            params: {
                pageNo: pages.currentPage,
                pageSize: 40,
            }
        });
        const clubRecords = clubRes.data.data.records;
        // 将社团列表数据存储到 tableData
        tableData.splice(0, tableData.length,...clubRecords);
        console.log('第一次获取的社团数据:', tableData);
        // 初始化各个分类的数据统计对象
        collageData.cs = 0;
        collageData.mapping = 0;
        collageData.literature = 0;
        collageData.hony = 0;
        typeData["0"] = 0;
        typeData["1"] = 0;
        typeData["2"] = 0;
        typeData["3"] = 0;
        typeData["4"] = 0;
        typeData["5"] = 0;

        for (let i = 0; i < tableData.length; i++) {
            if (tableData[i].collage === '计算机学院') {
                collageData.cs++;
            } else if (tableData[i].collage === '测绘学院') {
                collageData.mapping++;
            } else if (tableData[i].collage === '文学院') {
                collageData.literature++;
            } else {
                collageData.hony++;
            }

            if (tableData[i].tags === '自律互助类') {
                typeData["0"]++;
            } else if (tableData[i].tags === '创新创业类') {
                typeData["1"]++;
            } else if (tableData[i].tags === '学术科技类') {
                typeData["2"]++;
            } else if (tableData[i].tags === '思想政治类') {
                typeData["3"]++;
            } else if (tableData[i].tags === '志愿公益类') {
                typeData["4"]++;
            } else {
                typeData["5"]++;
            }

            let time = tableData[i].registerTime.split('-')[0];
            let flag = false;
            for (let j = 0; j < clubNum.length; j++) {
                if (time === clubNum[j].time) {
                    clubNum[j].num++;
                    flag = true;
                    break;  // 找到匹配的时间，就不用继续循环了，提高效率
                }
            }
            if (!flag) {
                clubNum.push({
                    'time': time,
                    'num': 1,
                });
            }

            numberNum.push({
                name: tableData[i].name,
                num: tableData[i].totalNumber
            });
        }

        // 使用数组的sort方法对clubNum进行排序，按照time属性从小到大排列
        clubNum.sort((a, b) => {
            return a.time - b.time;
        });

        console.log(numberNum);
    } catch (error) {
        console.error("Error fetching data: ", error);
    }
}

  export default defineComponent({
    name: 'Histogram',
    components: {Menu},
    setup() {
      const state = reactive({
        option1: {
          grid: {
            top: '20%',
            left: '53%',
            right: '10%',
            bottom: '6%',
            containLabel: true
          },
          series: [{
            label: {
              normal: {
                formatter: '{b|{b}：} {c} \n  {per|{d}%} ',
                rich: {
                }
              },
              emphasis: {
                show: true,
              }
            },
            // labelLine: {
            //     normal: {
            //         show: false
            //     }
            // },
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data:[{
              value: collageData.hony,
              name: '弘毅学堂'
            },
              {
                value: collageData.literature,
                name: '文学院'
              },
              {
                value: collageData.mapping,
                name: '测绘学院'
              },
              {
                value: collageData.cs,
                name: '计算机学院'
              },
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              normal: {
                length: 5,
                length2: 1,
                smooth: true,
              }
            },
          }],
        },
  
        option2: {
          grid: {
            top: '20%',
            left: '53%',
            right: '10%',
            bottom: '6%',
            containLabel: true
          },
          series: [{
            label: {
              normal: {
                formatter: '{b|{b}：} {c} \n  {per|{d}%} ',
                rich: {
                }
              },
              emphasis: {
                show: true,
              }
            },
            // labelLine: {
            //     normal: {
            //         show: false
            //     }
            // },
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data:[{
              value: typeData["3"],
              name: '思想政治类'
            },
              {
                value: typeData["2"],
                name: '学术科技类'
              },
              {
                value: typeData["5"],
                name: '文化体育类'
              },
              {
                value: typeData["1"],
                name: '创新创业类'
              },
              {
                value: typeData["4"],
                name: '志愿公益类'
              },
              {
                value: typeData["0"],
                name: '自律互助类'
              }
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              normal: {
                length: 5,
                length2: 1,
                smooth: true,
              }
            },
          }],
        },
  
        option3: {
          grid: {
            top: '10%',
            right: '3%',
            bottom: '15%',
            left: '3%',
            containLabel: true
          },
          xAxis: {
            name:'时间',
            data: clubNum.map(d=>d.time),
            axisLabel: {
            fontSize:13,
            padding:[10,0,0,0],
            color: 'rgba(0, 0, 0, 0.45)'
          },
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
            color: 'rgba(0, 0, 0, 0.35)',
            width: 1
            }
          }
        },
        yAxis: [
          {
          type: 'value',
            name:'数量',
          axisLabel: {
            color: 'rgba(0, 0, 0, 0.45)'
            },
          axisTick: {
            show: false
            },
          axisLine: {
            show: false
            },
          splitLine: {
            lineStyle: {
              type:'dashed',
              color: 'rgba(0, 0, 0, 0.15)'
              }
            }
          },
          {
          type: 'value',
          alignTicks: true,
          splitLine: {
            show: false
          },
          axisLabel: {
            color: 'rgba(0, 0, 0, 0.45)'
            }
          }
        ],
          series: [
        {
          name: 'bar',
          yAxisIndex: 0,
          type: 'bar',
          data: clubNum.map(val => {
            return {
              value: val.num,
            }
          }),
          barMaxWidth: 15,
          label: {
            show: true,
            color: "#5B8FF9",
            padding:[5,5,5,5]
          },
        },
      ]
        },
  
        option4: {
    grid: {
        top: '10%',
        right: '3%',
        bottom: '15%',
        left: '3%',
        containLabel: true
    },
    xAxis: {
        name: '社团名称',
        data: numberNum.map(d => d.name),
        axisLabel: {
            fontSize: 0,
            rotate: -90,
            verticalAlign: 'top',
            padding: [10, 0, 0, 0],
            color: 'rgba(0, 0, 0, 0.45)'
        },
        axisTick: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: 'rgba(0, 0, 0, 0.35)',
                width: 1
            }
        }
    },
    yAxis: [
        {
            name: '成员数量',
            type: 'value',
            axisLabel: {
                color: 'rgba(0, 0, 0, 0.45)'
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: 'rgba(0, 0, 0, 0.15)'
                }
            }
        },
        {
            type: 'value',
            alignTicks: true,
            splitLine: {
                show: false
            },
            axisLabel: {
                color: 'rgba(0, 0, 0, 0.45)'
            }
        }
    ],
    series: [
        {
            name: 'bar',
            yAxisIndex: 0,
            type: 'bar',
            data: numberNum.map(val => {
                return {
                    value: val.num,
                    label: {
                        position: val < 0? 'bottom' : 'top',
                    },
                    itemStyle: {
                        borderRadius: val < 0? [0, 0, 20, 20] : [20, 20, 0, 0]
                    },
                    // 添加tooltip配置，显示社团名称和对应的值
                    tooltip: {
                        trigger: 'item',
                        formatter: function (params) {
                            return `${params.name} : ${params.value}`;
                        }
                    }
                }
            }),
            barMaxWidth: 15,
            itemStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: -0.2,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {
                            offset: 1,
                            color: '#A7CEFF'
                        },
                        {
                            offset: 0,
                            color: '#5B8FF9'
                        }
                    ]
                }
            },
            label: {
                show: true,
                color: "#5B8FF9",
                padding: [5, 5, 5, 5]
            },
        },
        {
            data: numberNum.map(d => d.num),
            type: "line",
            smooth: true,
            symbol: 'circle',
            symbolSize: 10,
            lineStyle: {
                width: 4,
                color: "rgb(55, 200, 143)",
                shadowColor: 'rgba(55, 200, 143,.4)',
                shadowBlur: 8,
                shadowOffsetY: 10,
                shadowOffsetX: 0,
            },
            itemStyle: {
                color: "rgb(55, 200, 143)",
                borderColor: "#fff",
                borderWidth: 2,
                shadowBlur: 5,
                shadowColor: "rgba(5, 5, 5,.3)"
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                        offset: 0,
                        color: 'rgba(55, 200, 143,.4)'
                    },
                    {
                        offset: 1,
                        color: 'rgba(55, 200, 143, 0)'
                    }
                ]),

            },
            // 同样添加tooltip配置，显示社团名称和对应的值
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    return `${params.name} : ${params.value}`;
                }
            }
        }
    ],
    // 全局tooltip配置（可根据喜好调整样式等）
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        },
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: 'rgba(0, 0, 0, 0.3)',
        borderWidth: 1,
        padding: [5, 10, 5, 10],
        textStyle: {
            color: 'rgba(0, 0, 0, 0.8)'
        }
    }
}
      })
      const initCharts = () => {
        let myChart1 = echarts.init(document.getElementById('myChart1'))
        let myChart2 = echarts.init(document.getElementById('myChart2'))
        let myChart3 = echarts.init(document.getElementById('myChart3'))
        let myChart4 = echarts.init(document.getElementById('myChart4'))

        // 绘制图表
        myChart1.setOption(state.option1)
        myChart2.setOption(state.option2)
        myChart3.setOption(state.option3)
        myChart4.setOption(state.option4)
      }

      onMounted(() => {
        getList()
        initCharts()
      })
      // 新增代码：使用watch监听collageData变化，当变化时更新图表
      watch(() => collageData, (newCollageData) => {
        const newOption1 = {
          ...state.option1,
          series: [{
            ...state.option1.series[0],
            data: [
              {
                value: newCollageData.hony,
                name: '弘毅学堂'
              },
              {
                value: newCollageData.literature,
                name: '文学院'
              },
              {
                value: newCollageData.mapping,
                name: '测绘学院'
              },
              {
                value: newCollageData.cs,
                name: '计算机学院'
              },
            ]
          }]
        };
        const myChart1 = echarts.init(document.getElementById('myChart1'));
        myChart1.setOption(newOption1);
      }, { deep: true });


      watch(() => typeData, (newTypeData) => {
        const newOption2 = {
          ...state.option2,
          series: [{
            ...state.option2.series[0],
            data: [
              {
                value: newTypeData["4"],
                name: '思想政治类'
              },
              {
                value: newTypeData["2"],
                name: '学术科技类'
              },
              {
                value: newTypeData["5"],
                name: '文化体育类'
              },
              {
                value: newTypeData["1"],
                name: '创新创业类'
              },
              {
                value: newTypeData["3"],
                name: '志愿公益类'
              },
              {
                value: newTypeData["0"],
                name: '公益互助类'
              }
            ]
          }]
        };
        const myChart2 = echarts.init(document.getElementById('myChart2'));
        myChart2.setOption(newOption2);
      }, { deep: true });


      watch(() => clubNum, (newClubNum) => {
        const newOption3 = {
          ...state.option3,
          xAxis: {
            ...state.option3.xAxis,
            data: newClubNum.map(d => d.time)
          },
          series: [
            ...state.option3.series,
            {
              ...state.option3.series[0],
              data: newClubNum.map(val => {
                return {
                  value: val.num,
                  label: {
                    position: val < 0? 'bottom' : 'top',
                  },
                }
              })
            }
          ]
        };
        const myChart3 = echarts.init(document.getElementById('myChart3'));
        myChart3.setOption(newOption3);
      }, { deep: true });

      watch(() => numberNum, (newNumberNum) => {
        const newOption4 = {
          ...state.option4,
          xAxis: {
            ...state.option4.xAxis,
            data: newNumberNum.map(d => d.name)
          },
          series: [
            ...state.option4.series,
            {
              ...state.option4.series[0],
              data: newNumberNum.map(val => {
                return {
                  value: val.num,
                  label: {
                    position: val < 0? 'bottom' : 'top',
                  },
                  itemStyle: {
                    borderRadius: val < 0? [0, 0, 20, 20] : [20, 20, 0, 0]
                  }
                }
              })
            },
            {
              ...state.option4.series[1],
              data: newNumberNum.map(d => d.num)
            }
          ]
        };
        const myChart4 = echarts.init(document.getElementById('myChart4'));
        myChart4.setOption(newOption4);
      }, { deep: true });

      return {
        ...toRefs(state),
      }
    },
  })

  </script>
  

<style scoped>
.demo-basic {
  text-align: center;
}
.demo-basic .sub-title {
  margin-bottom: 10px;
  font-size: 18px;
  color: var(--el-text-color-secondary);
}
.demo-basic .demo-basic--circle{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 50px;
  margin-bottom: 20px;
}
.demo-basic .block {
  flex: 1;
}
.aside{
  width:200px;
  height:750px;
  background-color:#545c64;
}
.menu-list{
  margin-left: 15px;
}
.header{
  background: rgba(83, 88, 93, 0.15);
  height:80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.demo-form-inline .el-input {
  --el-input-width:120px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.changePage{
  margin-top: 50px;
  position: absolute;
  right: 50px;
}
.common-layout{
  background: rgba(217, 153, 217, 0.08);
}
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.circleChart{
    margin-top: -120px;
    margin-left: 600px;
    display: flex;
}

.rectChart1{
    margin-top: -20px;
    margin-left: 500px;
    display: flex;
}
.rectChart2{
  margin-top: -20px;
  margin-left: 500px;
  display: flex;
}

.chartItem{
    width: 400px;
    height: 400px;
    margin-right: 250px;
}

.rectIntroduction{
    margin-top: -50px;
    display: flex;
    font-size: 20px;
    font-weight: 700;
    color:#74808b;
    margin-left: 720px;
}
</style>